import { dynamicCSS } from './dynamicCss.js';
import { verify } from './verify.js';
import { rules } from './rules.js';
import { formatDate } from './formatDate.js';


dynamicCSS('/css/inputDate.css');


// 日历控件
var calendar = function (parent) {
    var _this = this;
    var html = '';
    html += '<div class="form_calendar">';
    html += '    <div class="form_calendar_conteoller">';
    html += '        <div class="form_calendar_select" title="选择年月">';
    html += '           <div class="form_calendar_selectName"></div>';
    html += '           <div class="form_calendar_selectIcon"></div>';
    html += '        </div>';
    html += '        <div class="form_calendar_buttons">';
    html += '           <div class="form_calendar_pre form_calendar_button" title="上个月"></div>';
    html += '           <div class="form_calendar_today form_calendar_button" title="今天"></div>';
    html += '           <div class="form_calendar_next form_calendar_button" title="下个月"></div>';
    html += '        </div>';
    html += '    </div>';
    html += '    <div class="form_calendar_yearlist"></div>';
    html += '    <div class="form_calendar_dayslist">';
    html += '       <div class="form_calendar_daysTitle">';
    html += '           <div class="form_calendar_weeks">周日</div>';
    html += '           <div class="form_calendar_weeks">周一</div>';
    html += '           <div class="form_calendar_weeks">周二</div>';
    html += '           <div class="form_calendar_weeks">周三</div>';
    html += '           <div class="form_calendar_weeks">周四</div>';
    html += '           <div class="form_calendar_weeks">周五</div>';
    html += '           <div class="form_calendar_weeks">周六</div>';
    html += '       </div>';
    html += '       <div class="form_calendar_daysBody">';
    html += '       </div>';
    html += '    </div>';
    html += '</div>';
    this.html = $(html);
    this.year_month = this.html.find('.form_calendar_selectName');


    this.nameBox = this.html.find('.form_calendar_select');
    this.html.click(function (e) {
        e.stopPropagation();
    });

    this.days = this.html.find('.form_calendar_daysBody');
    this.yearList = this.html.find('.form_calendar_yearlist');
    this.daysList = this.html.find('.form_calendar_dayslist');
    var today = new Date();
    this.today = {
        year: today.getFullYear(),
        month: today.getMonth() + 1,
        day: today.getDate(),
    };
    this.active = {
        year: null,
        month: null,
        day: null,
    };
    this.showDate = {
        year: null,
        month: null
    };
    this.parent = parent;
    this.pre = this.html.find('.form_calendar_pre');
    this.gotoToday = this.html.find('.form_calendar_today');
    this.next = this.html.find('.form_calendar_next');

    for (var i = 2017; i < this.today.year + 10; i++) {
        var yearItem = $('<div class="form_calendar_yearItem">' + i + '年</div>');
        (function (i, yearItem) {
            yearItem.click(function () {
                _this.yearList.find('.form_calendar_monthList').remove();
                $(this).after(_this.monthTemplate(i));
            });
        })(i, yearItem);
        _this.yearList.append(yearItem);
    };
    this.nameBox.click(function () {
        if (_this.yearList.css('display') == 'block') {
            _this.yearList.css('display', 'none');
            _this.daysList.css('display', 'block');
        } else {
            _this.yearList.css('display', 'block');
            _this.daysList.css('display', 'none');
        };
    });
    this.pre.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        var year = _this.showDate.year,
            month = _this.showDate.month;
        month -= 1;
        if (month == 0) {
            month = 12;
            year -= 1;
            if (year <= 2016) {
                return;
            }
        };
        _this.renderDayslist(year, month);
    });
    this.gotoToday.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        _this.renderDayslist(_this.today.year, _this.today.month);
    });
    this.next.click(function () {
        _this.yearList.css('display', 'none');
        _this.daysList.css('display', 'block');
        var year = _this.showDate.year,
            month = _this.showDate.month;
        month += 1;
        if (month == 13) {
            month = 1;
            year += 1;
            if (year >= 2056) {
                return;
            }
        };
        _this.renderDayslist(year, month);
    });
};
calendar.prototype = {
    constructor: this,
    render: function () {
        return this.html;
    },
    // 根据年月渲染当月日历
    renderDayslist: function (year, month) {
        if (year == 'error' || month == 'error') {
            year = this.today.year;
            month = this.today.month;
        } else {
            year = parseInt(year);
            month = parseInt(month);
        };

        // if (isNaN(year) || isNaN(month) || isNaN(day)) {
        //     year = this.today.year;
        //     month = this.today.month;
        // };

        // this.active.year = year;
        // this.active.month = month;
        // this.active.day = day;

        this.showDate.year = year;
        this.showDate.month = month;
        this.year_month.text(year + '年' + month + '月');
        var _this = this;
        this.days.empty();
        var isLeap = function (year) {
            return year % 4 == 0 ? (year % 100 != 0 ? 1 : (year % 400 == 0 ? 1 : 0)) : 0;
        };
        month = month - 1;
        var firstday = new Date(year, month, 1),
            dayOfWeek = firstday.getDay(),
            days_per_month = new Array(31, 28 + isLeap(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
            str_nums = Math.ceil((dayOfWeek + days_per_month[month]) / 7);
        for (var i = 0; i < str_nums; i += 1) {
            for (var k = 0; k < 7; k++) {
                var idx = 7 * i + k;
                var date = idx - dayOfWeek + 1;
                (date <= 0 || date > days_per_month[month]) ? date = '' : date = idx - dayOfWeek + 1;
                var day = $('<div class="form_calendar_day">' + date + '</div>');
                day.click(function () {
                    _this.activeEvent(year, month + 1, parseInt($(this).text()));
                });
                if (date == '') {
                    day.addClass('empty');
                };
                if (year == this.today.year && (month + 1) == this.today.month && date == this.today.day) {
                    day.addClass('today');
                };
                if (year == this.active.year && (month + 1) == this.active.month && date == this.active.day) {
                    day.addClass('active');
                };
                this.days.append(day);
            }
        };
    },
    // 选中当天
    activeEvent: function (year, month, day) {
        var value = year + '/' + month + '/' + day;
        this.active = {
            year: year,
            month: month,
            day: day,
        };
        if (this.parent.layout) {
            this.parent.layout.hideError();
        };
        $(document).click();
        this.parent.set(value, true);
        // this.renderDayslist(year, month);
    },
    // 直接选中月份
    monthTemplate: function (year) {
        var _this = this;
        var html = '';
        html += '<div class="form_calendar_monthList"></div>';
        html = $(html);
        var bindClick = function (i, event) {
            event.click(function () {
                _this.yearList.css('display', 'none');
                _this.daysList.css('display', 'block');
                _this.renderDayslist(year, i);
            });
        };
        for (var i = 1; i <= 12; i++) {
            var month = $('<div class="form_calendar_monthItem"></div>');
            bindClick(i, month);
            html.append(month.text(i + '月'));
        };
        html.append('<div style="clear:both"></div>');
        return html;
    }
};


var inputDate = function (options, layout) {
    this.options = $.extend({}, {
        'default': null,
        'size': 'normal',
        'readonly': false,
        'showType': 'YYYY年MM月DD日',
        'valueType': '/',
        'verify': {
            'text': '时间',
            'rules': []
        },
        'placeholder': '- 请选择 -',
        'onChange': function (e) { },
        'onError': function (e) { },
    }, options);

    // 事件集合
    this.event = {
        change: this.options.onChange,
        error: this.options.onError
    };

    var _this = this;
    var html = '';
    html += '   <div class="form_inputDate ' + (this.options.size ? this.options.size : '') + '">';
    html += '       <div class="form_inputDate_valueBox">';
    html += '           <input type="text" class="form_inputDate_value" placeholder="' + (this.options.placeholder) + '"/>'; //选中项
    html += '           <span></span>';
    html += '       </div>';
    html += '       <div class="form_inputDate_dateBox"></div>';
    html += '   </div>';
    this.html = $(html);
    this.nameBox = this.html.find('.form_inputDate_valueBox');
    this.dateBox = this.html.find('.form_inputDate_dateBox');
    this.valueEle = this.html.find('.form_inputDate_value');
    // 绑定change方法(支持拼音输入法)
    this.html.unbind().bind('change', function () {
        _this.change();
    });

    // 默认值
    this.value = null;

    // 兼容IE 的 placeHolder
    if (!!(this.options.placeholder) && !('placeholder' in document.createElement('input'))) {
        this.html.val(this.html.attr('placeholder', _this.options.placeholder));
        this.html.val(this.html.attr('placeholder')).addClass('ie-placeholder');
        this.html.bind('focus', function () {
            if (_this.html.val() == _this.html.attr('placeholder')) {
                _this.html.val("").removeClass('ie-placeholder');
            }
        }).bind('blur', function () {
            if (_this.html.val().length == 0) {
                _this.html.val(_this.html.attr('placeholder')).addClass('ie-placeholder');
            }
        });
    } else {
        this.html.attr('placeholder', this.options.placeholder);
    };
    // 初始化中,生成元素是否只读
    // this.readonly(this.options.readonly);
    // 添加默认值
    this.set(this.options.default);
    // 储存错误信息
    this.errorMessage = null;
    // 如果在 Form 对象中,则直接输出,不用Render(); 
    if (this.layout) {
        this.layout.append(this.html);
    };

    this.calendar = new calendar(this);
    this.dateBox.append(this.calendar.render());

    this.showOptionBox = false;
    this.layout = layout;
    // this.defaultValue();
    if (this.layout) {
        this.layout.append(this.html);
    };

    this.readonly(this.options.readonly);
};
// 绑定事件集合方法
inputDate.prototype.on = function (str, event) {
    if (this.event.hasOwnProperty(str)) {
        this.event[str] = event;
    };
    return this;
};
// 单独绑定 change 方法
inputDate.prototype.onChange = function (event) {
    this.event.change = event;
    return this;
};
// 单独绑定 error 方法
inputDate.prototype.onError = function (event) {
    this.event.error = event;
    return this;
};
// 当值发生变化时
inputDate.prototype.change = function () {
    // 改变变量作用域,使调用函数可以使用 this 方法
    // this.value = this.valueEle.val();
    var data = formatDate(this.options.valueType, this.valueEle.val())
    if (data != this.value && data != 'error') {
        this.set(this.valueEle.val());
        this.event.change.apply(this, [this.value]);
    } else {
        this.event.change.apply(this, [this.valueEle.val()]);
    };
    // 执行验证方法
    this.verify();
    return this;
};
inputDate.prototype.verify = function () {
    var value = formatDate(this.options.valueType, this.value);
    if (value == 'error') {
        var text = '非法的日期格式';
    } else {
        var text = rules(this.options.verify, this.value);
    };
    // 父级模板的显示错误信息及关闭错误信息
    if (this.layout) {
		if (text) {
			this.event.error.apply(this, [text, this.html.val()]);
			this.layout.showError(text);
			this.errorMessage = text;
		} else {
			this.layout.hideError();
			this.errorMessage = null;
		}
    } else {
        // 如果错误信息不为空,则触发error方法,并保留错误信息
        if (text) {
            this.event.error.apply(this, [text, this.valueEle.val()]);
            this.errorMessage = text;
        } else {
            // 如果错误信息为空,侧清空错误信息
            this.errorMessage = null;
        };
    };
    return this;
};
// 取消点击事件
inputDate.prototype.clearClick = function () {
    this.html.removeClass('active');
    this.showOptionBox = false;
    this.dateBox.css('display', 'none');
    $(document).unbind('click', documentClick);
    return this;
};
// 绑定点击事件
inputDate.prototype.bindClick = function () {
    var _this = this;
    _this.documentClick = function () {
        _this.html.removeClass('active');
        _this.showOptionBox = false;
        _this.dateBox.css('display', 'none');
        // _this.change();
        $(document).unbind('click', _this.documentClick);
    };

    this.nameBox.click(function (e) {
        e.stopPropagation();
        if (_this.showOptionBox) {
            _this.documentClick();
        } else {
            _this.html.addClass('active');
            _this.showOptionBox = true;
            _this.dateBox.css('display', 'block');
            if (_this.value) {
                _this.calendar.activeEvent(formatDate('YYYY', _this.value), formatDate('MM', _this.value), formatDate('DD', _this.value));
                _this.calendar.renderDayslist(formatDate('YYYY', _this.value), formatDate('MM', _this.value));
            } else {
                _this.calendar.renderDayslist();
            };
            // _this.valueEle.focus();
            // $(document).click();
            $(document).bind('click', _this.documentClick);
        };
    });
    return this;
};
// 只读状态
inputDate.prototype.readonly = function (isReadonly) {
    var _isReadonly = null;
    if (verify.is(isReadonly) == 'function') {
        _isReadonly = isReadonly();
    };
    _isReadonly = !!isReadonly;
    // this.options.readonly = _isReadonly;
    if (_isReadonly) {
        this.clearClick();
    } else {
        this.bindClick();
    };
    return this;
};
// 为输入框赋值
inputDate.prototype.set = function (data, doChange) {
    if (data === null) {
        return;
    };
    this.value = data;
    // 格式化取值赋值对象
    if (this.value) {
        this.value = formatDate(this.options.valueType, data);
        if (this.value != 'error') {
            this.valueEle.val(formatDate(this.options.showType, data));
        };
    };
    if (doChange) {
        this.change();
    };
    return this;
};
// 取值方法
inputDate.prototype.get = function (callBack, ignore) {
    if (ignore) {
        callBack(this.value);
    } else {
        this.verify();
        if (this.errorMessage) {
            callBack(this.errorMessage);
        } else {
            callBack(false, this.value);
        };
    };
    return this;
};
export { inputDate };
